package com.mxf.code.state_factory.service.impl;

import com.mxf.code.state_factory.pojo.Order;
import com.mxf.code.state_factory.pojo.OrderState;
import com.mxf.code.state_factory.pojo.OrderStateFactory;
import com.mxf.code.state_factory.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * @version 1.0
 * @date 2021/6/9 21:37
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderStateFactory factory;

    @Override
    public void saveOrUpdateOrder(Order order) {
        //查找出原来的订单
        Order oldOrder = this.mockGetById(order.getId());
        if (Objects.isNull(oldOrder)) {
            //新增
            this.mockSave(order);
            if (Objects.nonNull(order.getStatus())) {
                //调用状态机
                factory.getState(order.getStatus()).handle(order, null);
            }
            return;
        }
        //修改
        OrderState orderState = Objects.isNull(order.getStatus()) ? factory.getState(oldOrder.getStatus()) :
                factory.getState(order.getStatus());
        orderState.handle(order, oldOrder);
    }

    private void mockSave(Order order) {

    }

    private Order mockGetById(Long id) {
        Order order = new Order();
        order.setId(id);
        order.setPrice(new BigDecimal("0"));
        order.setStatus(0);
        order.setCreateTime(new Date());
        return order;
    }
}